import cv2
import numpy as np
import random

font = [
    cv2.FONT_HERSHEY_SIMPLEX,
    cv2.FONT_HERSHEY_COMPLEX_SMALL,
    cv2.FONT_ITALIC
]


def rand_color(th1, th2):
    return (np.random.randint(th1, th2), np.random.randint(th1, th2), np.random.randint(th1, th2))


def random_code(n=4):
    ch = []
    ch += [c for c in range(48, 58)]  # 数字
    ch += [c for c in range(65, 91)]  # 大写字母
    return "".join([chr(random.choice(ch)) for c in range(n)])


def rand_pos(x_start, x_end, y_start, y_end):
    return (np.random.randint(x_start, x_end),
            np.random.randint(y_start, y_end))


def create_verificode(img_heigth, img_width, code, line_num=10):
    img = np.random.randint(200, 255, (img_heigth, img_width, 3), np.uint8)
    for i in range(line_num):
        img = cv2.line(img,
                       rand_pos(0, img_width, 0, img_heigth),
                       rand_pos(0, img_width, 0, img_heigth),
                       rand_color(150, 200),
                       np.random.randint(1, 2))
    x_dis = int(img_width / len(code))
    y_dis = int(img_heigth / 4.)
    x_pos = 0
    y_pos = img_heigth * 0.75
    for i, c in enumerate(code):
        cv2.putText(
            img, c,
            (np.random.randint(x_pos, x_pos + x_dis / 4), np.random.randint(y_pos, y_pos + y_dis)),
            random.choice(font),
            1,
            rand_color(0, 150),
            1,
            cv2.LINE_AA
        )
        x_pos += x_dis

    return img


def save_img(img, path):
    return cv2.imwrite(path, img)


if __name__ == "__main__":
    size = (35, 101)
    code = random_code()
    img = create_verificode(*size, code)
    cv2.namedWindow("verify code", cv2.WINDOW_NORMAL)
    cv2.imshow("verify code", img)
    print(code)
    cv2.waitKey(0)
